package com.teng.web.servlet;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebFilter("/api/*")
public  class Authority implements Filter {
	//白名单
		Set<String> whiteList=new HashSet<>();

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		whiteList.add("/public-api/user/login");
		
	}
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req=(HttpServletRequest) request;
		HttpServletResponse resp=(HttpServletResponse) response;
		//1拿出请求的url
		String url=req.getRequestURI();
		String name=req.getContextPath();
		url=url.substring(name.length());
		//2判断是否是白名单，如果是直接通过
		if(isInWhiteList(url)) {
			chain.doFilter(req, resp);
			return;
		}
		//3如果不是，判断是否已登陆，如果是直接通过
		if(isLogin(req)) {
			chain.doFilter(req, resp);
			return;
		}
		//4如果未通过，返回未授权(非法访问)
		 resp.sendError(403,"非法访问");
	}
	private boolean isInWhiteList(String url) {
		return whiteList.contains(url);
	}
	private  boolean isLogin(HttpServletRequest req) {
		HttpSession session=req.getSession(false);
		if(session==null) {
			return false;
		}
		Object value=session.getAttribute("YANZHENG");
		if(value==null) {
			return false;
		}
		return true;
	}
}
